package com.ws.mbp.springsecuritydemo.config;

import com.ws.mbp.springsecuritydemo.utils.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return new AntPathRequestMatcher("/swagger-ui.html").matches(request)||
                new AntPathRequestMatcher("/swagger-ui/**").matches(request)
                || new AntPathRequestMatcher("/v3/api-docs/**").matches(request)
                || new AntPathRequestMatcher("/api/auth/**").matches(request);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("jwtfilter拦截"+request.getServletPath()+"--"+request.getHeader("Authorization"));
        // 放行登录接口 放行swagger相关

//        if ("/api/auth/login".equals(request.getServletPath())) {
//            filterChain.doFilter(request, response);
//            return;
//        }

        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        final String username;

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        jwt = authHeader.substring(7);
        username = jwtUtils.extractUsername(jwt);

        //不再查询数据库直接使用前端传过来的token数据
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 直接从 JWT 中提取角色信息
            List<SimpleGrantedAuthority> authorities = jwtUtils.extractAuthorities(jwt);

            // 创建 Authentication 对象，无需查询数据库
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                    username,  // 注意这里使用 username 而非 userDetails
                    null,
                    authorities
            );

            System.out.println("用户角色: " + authorities);
            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authToken);
        }


        filterChain.doFilter(request, response);
    }
}
